<template>
  <div class="news-detail-container">
    <!-- 新闻头部 -->
    <div class="news-header">
      <div class="news-title">{{ content.title }}
        <el-tag :type="getStatusTagType(content.statusCode)" v-if="content.username == authStore.user.nickname">
         {{ content.statusCode == 1 ? '草稿' : (content.statusCode == 2 ? '审核中' : '已发布')}}
        </el-tag>
        <el-button type="primary"  @click="goBack" style="float: right; margin-top: 10px" size="">返回</el-button>

        <el-row style="float: right; margin: 10px 5px" v-if="content.username == authStore.user.nickname">
          <el-button type="success" @click="publishContent(contentId)" v-if="content.statusCode == 1">
            <i class="el-icon-plus"></i> 发布
          </el-button>
          <el-button type="danger" @click="handledelete(contentId)">
            <i class="el-icon-plus"></i> 删除
          </el-button>
          <el-button type="warning" @click="handleEdit(contentId)">
            <i class="el-icon-plus"></i> 编辑
          </el-button>
        </el-row>

      </div>

      <div class="news-meta">
        <span class="news-source">{{ content.username }}</span>
        <span class="news-time">{{ formatDate(content.publishTime) }}</span>
        <span class="news-views">{{ content.readCount }}阅读</span>
        <div class="news-tags" v-if="content.categoryName">
          <span class="tag">{{ content.categoryName }}</span>
        </div>
      </div>
    </div>

    <!-- 新闻正文 -->
    <div class="news-content">
      <div class="content-summary" v-if="content.summary">
        <p>{{ content.summary }}</p>
      </div>
      <div class="content-body" v-html="content.content"></div>
    </div>

    <!-- 新闻底部操作区 -->
    <div class="news-footer">
      <div class="news-actions">
        <button class="action-btn like" :class="{ active: isLiked }" @click="handleLike">
          <span class="icon">👍</span>
          <span class="count">{{ content.likeCount }}</span>
        </button>
        <button class="action-btn comment" @click="scrollToComments">
          <span class="icon">💬</span>
          <span class="count">{{ content.commentCount }}</span>
        </button>
        <button class="action-btn share" @click="handleShare">
          <span class="icon">↗️</span>
          <span>分享</span>
        </button>
        <!-- 举报 -->
        <button class="action-btn report" @click="reportContent">
          <span class="icon">🚨</span>
          <span>举报</span>
        </button>
        <!-- 搜索 -->
      </div>
    </div>

    <!-- 评论区 -->
    <div class="comments-section" ref="commentsSection">
      <div class="comments-header">
        <h3>评论 <span class="comment-count">{{ content.commentCount }}</span></h3>
      </div>
      <!-- 评论列表 -->
      <div class="comments-list" v-if="comments.length > 0">
        <div class="comment-item" v-for="comment in comments" :key="comment.id">
          <div class="comment-avatar">
            {{ defaultAvatar }}
          </div>
          <div class="comment-content">
            <div class="comment-user">
              <span class="username">{{ comment.username }}</span>
              <span class="time">{{ formatShortDate(comment.createTime) }}</span>
            </div>
            <div class="comment-text">{{ comment.content }}</div>
            <div class="comment-actions">
              <button class="reply-btn" @click="replyToComment(comment)">回复</button>
              <button class="like-btn" @click="likeComment(comment.id)">
                <span>👍 {{ comment.likeCount || 0 }}</span>
              </button>
              <button class="report-btn" @click="reportComment(comment.id)">举报</button>
            </div>

            <!-- 子评论区域 -->
            <div class="replies-container" v-if="comment.replies && comment.replies.length > 0">
              <div class="reply-item" v-for="reply in visibleReplies(comment.id)" :key="reply.id">
                <div class="comment-avatar">
                  {{ defaultAvatar }}
                </div>
                <div class="comment-content">
                  <div class="comment-user">
                    <span class="username">{{ reply.username }}</span>
                    <span class="time">{{ formatShortDate(reply.createTime) }}</span>
                  </div>
                  <div class="comment-text">{{ reply.content }}</div>
                  <div class="comment-actions">
                    <button class="reply-btn" @click="replyToComment(reply)">回复</button>
                    <button class="like-btn" @click="likeComment(reply.id)">
                      <span>👍 {{ reply.likeCount || 0 }}</span>
                    </button>
                    <button class="report-btn" @click="reportComment(reply.id)">举报</button>
                  </div>
                </div>
              </div>

              <div class="reply-controls" v-if="comment.replies.length > 2">
                <button
                  v-if="hasMoreReplies(comment.id)"
                  class="show-more-btn"
                  @click="loadMoreReplies(comment.id)"
                >
                  查看更多回复 ({{ remainingReplies(comment.id) }})
                </button>
                <button
                  v-if="showCollapse(comment.id)"
                  class="collapse-btn"
                  @click="collapseReplies(comment.id)"
                >
                  收起
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div class="empty-comments" v-else>
        <p>暂无评论，快来发表你的看法吧~</p>
      </div>
       <!-- 评论发表框 -->
       <div class="comment-editor">
        <textarea
          v-model="commentText"
          placeholder="写下你的评论..."
          rows="3"
          ref="commentInput"
        ></textarea>
        <div class="editor-actions">
          <button class="submit-btn" @click="submitComment">发布评论</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useAuthStore } from '@/stores/auth'
import { ref, onMounted, nextTick } from 'vue'
import { getContentDetailInfo, getComments, submitComment as apiSubmitComment,deleteContentById, updateStatus} from '@/api/contents'
import { useRoute,useRouter  } from 'vue-router'
const authStore = useAuthStore()
const route = useRoute()
const router = useRouter()
const contentId = route.params.contentId
const content = ref({})
const comments = ref([])
const commentText = ref('')
const isLiked = ref(false)
const commentsSection = ref(null)
const commentInput = ref(null)
const replyingTo = ref(null)
const defaultAvatar = '👤'
const repliesState = ref({})

// 初始化评论状态
const initCommentState = (commentId) => {
  if (!repliesState.value[commentId]) {
    repliesState.value[commentId] = {
      visibleCount: 1,   // 默认显示2条
      pageSize: 5       // 每次加载10条
    }
  }
}

// 获取当前可见的子评论
const visibleReplies = (commentId) => {
  initCommentState(commentId)
  const state = repliesState.value[commentId]
  const comment = findCommentById(commentId)
  return comment.replies.slice(0, state.visibleCount)
}

// 根据ID查找评论（包括子评论）
const findCommentById = (commentId) => {
  // 先在父评论中查找
  let comment = comments.value.find(c => c.id === commentId)
  if (comment) return comment

  // 在子评论中查找
  for (const parent of comments.value) {
    if (parent.replies && parent.replies.length > 0) {
      const found = parent.replies.find(r => r.id === commentId)
      if (found) return found
    }
  }
  return null
}

// 是否还有更多回复可加载
const hasMoreReplies = (commentId) => {
  const comment = findCommentById(commentId)
  const state = repliesState.value[commentId]
  return comment.replies.length > state.visibleCount
}

// 剩余未显示的回复数量
const remainingReplies = (commentId) => {
  const comment = findCommentById(commentId)
  const state = repliesState.value[commentId]
  return comment.replies.length - state.visibleCount
}

// 加载更多回复
const loadMoreReplies = (commentId) => {
  const state = repliesState.value[commentId]
  const comment = findCommentById(commentId)

  // 计算新的可见数量（不超过总数量）
  const newVisibleCount = Math.min(
    state.visibleCount + state.pageSize,
    comment.replies.length
  )

  repliesState.value = {
    ...repliesState.value,
    [commentId]: {
      ...state,
      visibleCount: newVisibleCount
    }
  }
}

// 是否显示收起按钮
const showCollapse = (commentId) => {
  const state = repliesState.value[commentId]
  return state && state.visibleCount > 2
}

// 收起回复
const collapseReplies = (commentId) => {
  repliesState.value = {
    ...repliesState.value,
    [commentId]: {
      ...repliesState.value[commentId],
      visibleCount: 1 // 重置为默认显示2条
    }
  }
}

const fetchContentDetail = async () => {
  try {
    const res = await getContentDetailInfo(contentId)
    content.value = res.data.data
  } catch (error) {
    console.error('获取内容详情失败:', error)
  }
}

const fetchComments = async () => {
  try {
    const res = await getComments(contentId)
    console.log('获取到的评论数据:', res.data.data);

    // 将评论分为父评论和子评论
    const allComments = res.data.data.map(comment => ({
      id: comment.commentId,
      username: comment.userName,
      avatar: comment.userAvatar,
      content: comment.commentText,
      likeCount: comment.likeCount,
      createTime: comment.createTime,
      parentCommentId: comment.parentCommentId,
      replies: [] // 用于存储子评论
    })) || []

    // 构建评论树
    const parentComments = allComments.filter(comment => !comment.parentCommentId)
    const childComments = allComments.filter(comment => comment.parentCommentId)

    // 将子评论添加到对应的父评论中
    childComments.forEach(child => {
      const parent = allComments.find(c => c.id === child.parentCommentId)
      if (parent) {
        parent.replies.push(child)
      }
    })

    comments.value = parentComments

    // 初始化所有父评论的状态
    parentComments.forEach(comment => {
      initCommentState(comment.id)
    })
  } catch (error) {
    console.error('获取评论失败:', error)
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatShortDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const now = new Date()
  const diff = now - date

  // 小于1分钟
  if (diff < 60000) return '刚刚'
  // 小于1小时
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  // 今天
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }
  // 昨天
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }
  // 更早
  return date.toLocaleDateString('zh-CN', {
    month: 'short',
    day: 'numeric'
  })
}

const handleLike = async () => {
  try {
    isLiked.value = !isLiked.value
    content.value.likeCount += isLiked.value ? 1 : -1
  } catch (error) {
    console.error('点赞失败:', error)
  }
}

const scrollToComments = () => {
  commentsSection.value?.scrollIntoView({ behavior: 'smooth' })
}

const handleShare = () => {
  console.log('分享新闻')
}

const replyToComment = (comment) => {
  replyingTo.value = comment.id
  commentText.value = `@${comment.username} `
  nextTick(() => {
    commentInput.value.focus()
    scrollToComments()
  })
}

const submitComment = async () => {
  if (!commentText.value.trim()) return

  try {
    await apiSubmitComment(contentId, commentText.value, replyingTo.value)
    commentText.value = ''
    replyingTo.value = null
    fetchComments()
    content.value.commentCount += 1
  } catch (error) {
    console.error('评论提交失败:', error)
  }
}

const likeComment = (commentId) => {
  console.log('点赞评论:', commentId)
}

const reportComment = (commentId) => {
  console.log('举报评论:', commentId)
}

const reportContent = () => {
  console.log('举报内容')
}
// 编辑
const handleEdit = (id) =>{
  console.log("------------"+id)
  router.push({
    name: 'addContent',
    params: { id }
  });
}
//返回
const goBack = () =>{
  router.go(-1);
}
// 获取状态标签类型
const getStatusTagType = (statusCode) => {
  const map = {
    3: 'success', // 已发布
    2: 'warning', // 待审核
    1: 'info'   // 草稿
  };
  return map[statusCode] || 'info';

}
//删除
const handledelete = async (contentId) =>{

  try {
    await deleteContentById(contentId)
  } catch (error) {
    console.error('删除失败:', error)
  }
}
//修改状态
const publishContent = async (contentId) =>{
  console.log("------********------"+contentId)
  try {
    await updateStatus(contentId)
  } catch (error) {
    console.error('修改状态:', error)
  }
}

onMounted(() => {
  fetchContentDetail()
  fetchComments()
})
</script>

<style scoped>
.news-detail-container {
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  line-height: 1.6;
  width: -webkit-fill-available;
}

.news-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.news-title {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 16px;
  line-height: 1.4;
}

.news-meta {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
  gap: 16px;
}

.news-source {
  color: #1890ff;
  font-weight: 500;
}

.news-content {
  margin-bottom: 32px;
}

.content-summary {
  padding: 12px 16px;
  background-color: #f8f8f8;
  border-left: 3px solid #1890ff;
  margin-bottom: 20px;
  color: #666;
  font-size: 15px;
}

.content-body {
  font-size: 16px;
  line-height: 1.8;
}

.content-body :deep(p) {
  margin-bottom: 1.5em;
}

.content-body :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  margin: 16px 0;
  display: block;
}

.content-body :deep(h2),
.content-body :deep(h3) {
  margin: 24px 0 16px;
  font-weight: bold;
}

.news-footer {
  margin-bottom: 40px;
  padding-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;
}

.news-actions {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: #f5f5f5;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 14px;
}

.action-btn:hover {
  background: #e8e8e8;
}

.action-btn.active {
  background: #e6f7ff;
  color: #1890ff;
}

.action-btn .icon {
  font-size: 16px;
}

.news-tags {
  display: flex;
  gap: 8px;
}

.tag {
  padding: 4px 10px;
  background: #f0f7ff;
  color: #1890ff;
  border-radius: 4px;
  font-size: 12px;
}

/* 评论区样式 */
.comments-section {
  margin-top: 40px;
}

.comments-header {
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.comments-header h3 {
  font-size: 20px;
  font-weight: 600;
}

.comment-count {
  color: #1890ff;
}

.comment-editor {
  margin-bottom: 30px;
}

.comment-editor textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none;
  font-family: inherit;
  font-size: 14px;
  margin-bottom: 12px;
}

.comment-editor textarea:focus {
  outline: none;
  border-color: #1890ff;
}

.editor-actions {
  display: flex;
  justify-content: flex-end;
}

.submit-btn {
  padding: 8px 20px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.2s;
}

.submit-btn:hover {
  background: #40a9ff;
}

/* 评论列表 */
.comments-list {
  border-top: 1px solid #f0f0f0;
}

.comment-item {
  display: flex;
  padding: 16px 0;
  border-bottom: 1px solid #f5f5f5;
}

.comment-avatar {
  margin-right: 12px;
}

.comment-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.comment-content {
  flex: 1;
}

.comment-user {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.username {
  font-weight: 500;
  margin-right: 10px;
}

.time {
  font-size: 12px;
  color: #999;
}

.comment-text {
  margin-bottom: 10px;
  font-size: 15px;
  line-height: 1.6;
}

.comment-actions {
  display: flex;
  gap: 16px;
}

.reply-btn,
.like-btn {
  background: none;
  border: none;
  color: #666;
  font-size: 13px;
  cursor: pointer;
  padding: 0;
}

.reply-btn:hover,
.like-btn:hover {
  color: #1890ff;
}

.empty-comments {
  text-align: center;
  padding: 40px 0;
  color: #999;
}

/* 子评论样式 */
.replies-container {
  margin-top: 16px;
  padding-left: 52px;
  position: relative;
}

.replies-container::before {
  content: '';
  position: absolute;
  left: 16px;
  top: 0;
  bottom: 0;
  width: 2px;
  background-color: #f0f0f0;
}

.reply-item {
  display: flex;
  padding: 12px 0;
  position: relative;
}

.reply-item .comment-avatar {
  width: 32px;
  height: 32px;
  margin-right: 12px;
}

.reply-item .comment-avatar img {
  width: 32px;
  height: 32px;
}

.reply-item .comment-content {
  flex: 1;
}

.reply-item .comment-user {
  margin-bottom: 6px;
}

.reply-item .comment-text {
  font-size: 14px;
  margin-bottom: 8px;
}

.reply-item .comment-actions {
  gap: 12px;
}

.reply-item .reply-btn,
.reply-item .like-btn,
.reply-item .report-btn {
  font-size: 12px;
}

/* 回复控制按钮 */
.reply-controls {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}

.show-more-btn, .collapse-btn {
  padding: 6px 12px;
  font-size: 13px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.show-more-btn {
  background: none;
  border: 1px solid #e0e0e0;
  color: #666;
}

.show-more-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
  background: #f5f5f5;
}

.collapse-btn {
  background: #f5f5f5;
  border: 1px solid #f5f5f5;
  color: #666;
}

.collapse-btn:hover {
  background: #e0e0e0;
  border-color: #e0e0e0;
}

/* 举报按钮样式 */
.report-btn {
  background: none;
  border: none;
  color: #666;
  font-size: 13px;
  cursor: pointer;
  padding: 0;
  margin-left: 16px;
}

.report-btn:hover {
  color: #f5222d;
}

/* 文章头部的举报按钮特殊样式 */
.news-meta .report-btn {
  color: #999;
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 4px;
}

.news-meta .report-btn:hover {
  background: #fff1f0;
  color: #f5222d;
}

@media (max-width: 768px) {
  .news-detail-container {
    padding: 15px;
  }

  .news-title {
    font-size: 24px;
  }

  .news-meta {
    flex-wrap: wrap;
    gap: 8px;
  }

  .news-actions {
    gap: 12px;
  }

  .action-btn {
    padding: 6px 12px;
  }

  .replies-container {
    padding-left: 40px;
  }
}
</style>
